<template>
  <div>
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchForm" :rule="searchFormRules" :key="key">
        <!-- <template #field-modelInfo="scope">
          <el-cascader v-model="cascaderData" :props="cascaderProps" :placeholder="scope.data.rule.props.placeholder"
            :clearable="scope.data.rule.props.clearable" :show-all-levels="false" @change="cascaderDataChange"
            :style="{ width: '100%' }" />
        </template> -->
        <template #field-expireDate="scope">
          <el-form-item>
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%;" v-model="searchForm.expireDate"
              @change="dateChange" />
          </el-form-item>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button type="primary" :icon="Plus" @click="add" v-auth="'system.serial.create'">添加</el-button>
        <el-button type="primary" plain @click="importInfo" v-auth="'system.serial.import'">导入</el-button>
        <el-button type="primary" plain @click="DebounceGetTemplates" v-auth="'system.serial.import'">下载导入模板</el-button>
        <el-button type="primary" plain @click="transferInfo" v-auth="'system.serial.transfer'">转移序列号</el-button>
        <!-- <sj-button type="primary" :icon="Plus" @click="importInfo">导入</sj-button>
        <sj-button type="primary" :icon="Plus" @click="getTemplates">下载导入模板</sj-button>
        <sj-button type="primary" :icon="Plus" @click="transferInfo">转移序列号</sj-button> -->
        <!-- <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button> -->
      </div>
      <pure-table class="mt-5" border :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip
        @selection-change="selectionChange" :isShowPag="false">

        <template #deviceId="{ row }">
          {{ isNullOrEmpty( row.deviceId || '--' ) }}
        </template>
        <template #status="{ row }">
          <el-tag :type="PRODUCT_STATUS[row.status]?.type">{{ isNullOrEmpty( PRODUCT_STATUS[row.status]?.label ) }}</el-tag>
        </template>
        <template #useInfo="{ row }">
          {{ row.useType == 1 ? `项目-${row.useUnityName}-${row.useProjectName}` :
            row.useType == 2 ? `个体-${row.useNickName}` : '--' }}
        </template>
        <template #supUnityIds="{ row }">
          {{ isNullOrEmpty( row?.unityInfo?.map((item) => item.unityName).join(" ") ) }}
        </template>
        <template #action="{ row }">
          <el-space>
            <!-- <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link> -->
            <sj-link :disabled="isDisabled(row.unityId)" custom-type="sblue" :underline="false" @click="edit(row)" v-auth="'system.serial.update'">编辑</sj-link>
            <sj-link custom-type="sred" :underline="false" @click="deletes(row)" v-auth="'system.serial.remove'">删除</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'

import { isDisabled } from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import importSerialNumbe from './import-serial-numbe.vue'
import transferSerialNumber from './transfer-serial-number.vue'
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo, getProductTypeSelectList, getProductModelSelectList, transferSerial, importSerial, downloadTemplate } from '@/api/manage/resource-management/serial-number-management/index';
import { getFactorySelectList } from '@/api/manage/product-management/product-type/index'
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
import { PRODUCT_STATUS, PRODUCT_STATUS_FORMCREATE, PRODUCT_USER_TYPE } from "@/constant/product-management";
import type { CascaderProps } from 'element-plus'
import { getUnitList } from '@/api/manage/units-manager/units-manager/index';
import { UNIT_TYPE_Map } from '@/constant/index'

const searchForm = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const cascaderData = ref([])
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'SN', title: titles.SN, value: null, props: {
      placeholder: prompt.SN, clearable: true
    }
  },
  {
    type: 'input', field: 'deviceId', title: titles.deviceId, value: null, props: {
      placeholder: prompt.deviceId, clearable: true
    }
  },
  // {
  //   type: 'fieldComponent', field: 'modelInfo', title: titles.modelInfo, value: null, props: {
  //     placeholder: prompt.modelInfo, clearable: true
  //   }
  // },
  {
    type: 'fieldComponent', field: 'expireDate', title: titles.expireDate, value: null, props: {
      placeholder: prompt.expireDate, clearable: true
    }
  },
  {
    type: 'input', field: 'personal', title: titles.personal, value: null, props: {
      placeholder: prompt.personal, clearable: true
    }
  },
  {
    type: 'input', field: 'unity', title: titles.unity, value: null, props: {
      placeholder: prompt.unity, clearable: true
    }
  },
  {
    type: 'select', field: 'status', title: titles.status, value: null,
    options: PRODUCT_STATUS_FORMCREATE,
    props: {
      placeholder: prompt.status, clearable: true,
    }
  },
  // {
  //   type: 'input', field: 'activeName', title: titles.activeName, value: null, props: {
  //     placeholder: prompt.activeName, clearable: true
  //   }
  // },
  { type: 'string', field: 'expireStart', title: 'expireStart', hidden: true },
  { type: 'string', field: 'expireEnd', title: 'expireEnd', hidden: true },
  { type: 'number', field: 'factoryId', title: 'page', hidden: true },
  { type: 'number', field: 'productId', title: 'page', hidden: true },
  { type: 'number', field: 'modelId', title: 'page', hidden: true },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];

const roleTableConfig = [
  { type: "selection", align: 'center' },
  { prop: 'id', width:  100, label: titles.id, fixed: 'left' },
  { prop: 'unityName', label: titles.unityName, minWidth: 150 },
  { prop: 'SN', label: titles.SN, minWidth: 150 },
  // { prop: 'factoryName', label: titles.factoryName },
  { prop: 'productName', label: titles.productName, minWidth: 100 },
  { slot: 'deviceId', label: titles.deviceId , minWidth: 100},
  { slot: 'useInfo', label: titles.useInfo, minWidth: 100 },
  { slot: 'status', label: titles.status, minWidth: 100 },
  { slot: 'supUnityIds', label: titles.supUnityIds, minWidth: 150 },
  { prop: 'expireDate', label: titles.expireDate, minWidth: 100 },
  // { slot: 'userType', label: titles.userType },
  // { prop: 'useName', label: titles.useName },
  // { prop: 'endDate', label: titles.endDate },
  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];
const superviseUnityMap = ref([])
const selectionData = ref([]);
const cascaderProps: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node
    console.log(level);
    if (level == 0) {
      getFactorySelectList().then(res => {
        let nodes = res.result.map((item) => ({
          value: item.factoryId,
          label: item.factoryName,
        }))
        resolve(nodes)
      })
    } else if (level == 1) {
      getProductTypeSelectList({ factoryId: node.value }).then(res => {
        let nodes = res.result.map((item) => ({
          value: item.productId,
          label: item.productName,
        }))
        resolve(nodes)
      })
    } else if (level == 2) {
      getProductModelSelectList({ productId: node.value }).then(res => {
        let nodes = res.result.map((item) => ({
          value: item.modelId,
          label: item.modelName,
          leaf: true
        }))
        resolve(nodes)
      })
    }
  },
}

onMounted(() => {
  getTableList()
  // getUnitList({ unityType: UNIT_TYPE_Map.monitor }).then(res => {
  //   res.result.forEach(item => {
  //     superviseUnityMap.value[item.id]=item.unityName
  //   })
  //   console.log(superviseUnityMap.value);
  // })
});
// 获取列表数据
const getTableList = () => {
  getList(searchForm.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchForm.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `序列号详情`,
    hideFooter: true,
    width: "1100px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog('添加序列号')
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑序列号", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加序列号", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm(),
          cascaderKey: 0
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result
            // res.result.superviseUnityIds = res.result.superviseUnityIds.map(item => item.id)
            options.props.formInline = res.result
            options.props.formInline.modelInfo = [res.result.factoryId, res.result.productId, res.result.modelId]
          }
        }).finally(() => {
          options.props.isLoading = false
          // formRef.value.loadCascaderOptions()
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: {}
        }
        options.props.formInline.modelInfo = [null,null,null]

        // formRef.value.loadCascaderOptions()
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加序列号") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
// const cascaderDataChange = (e) => {
//   if (e.length == 3) {
//     searchForm.value.factoryId = e[0]
//     searchForm.value.productId = e[1]
//     searchForm.value.modelId = e[2]
//   } else {
//     searchForm.value.factoryId = ''
//     searchForm.value.productId = ''
//     searchForm.value.modelId = ''
//   }
// }
const selectionChange = data => {
  selectionData.value = data;
};
const transferInfo = () => {
  if (selectionData.value.length == 0) {
    message('请选择要转移的序列号', { type: 'warning' })
    return
  }
  addDialog({
    title: `序列号转移`,
    width: "800px",
    draggable: true,
    props: {
      form: {
        ids: selectionData.value.map(item => item.id),
        unityId: null
      },
      isLoading: false,
      transferList: selectionData.value
    },
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(transferSerialNumber, { ref: formRef }),
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          DebounceTransforInfo(options.props.form).then(res => {
            if (res.code == 200) {
              chores();
            }
            options.props.isLoading = false;
          }).catch((err) => {
            if (err !== '请求中') {
              options.props.isLoading = false;
            }
          })
        }
      })
    }
  });
}
const importInfo = () => {
  addDialog({
    title: `文件导入`,
    width: "800px",
    draggable: true,
    props: {
      form: {
        file: null,
        modelInfo: [null,null,null]
      }
    },
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(importSerialNumbe, { ref: formRef }),
    openAutoFocus({ options, index }) {
      // formRef.value.loadCascaderOptions()
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          let formData = new FormData();
          for (let key in options.props.form) {
            formData.append(key, options.props.form[key]);
          }
          console.log(options.props.form);

          DebounceImportSerial(formData).then(res => {
            if (res.code == 200) {
              chores();
            }
            options.props.isLoading = false;
          }).catch((err) => {
            if (err !== '请求中') {
              options.props.isLoading = false;
            }
          })
        }
      })
    }
  });
}
const getTemplates = () => {
  downloadTemplate({ type: 1 }).then(res => {
    console.log(res);
    const url = window.URL.createObjectURL(res)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', '序列号导入模板.xlsx')
    document.body.appendChild(link)
    link.click()
    link.remove()
  })
}
const dateChange = (e) => {
  console.log(e);
  if (e) {
    searchForm.value.expireStart = e[0];
    searchForm.value.expireEnd = e[1];
  } else {
    searchForm.value.expireStart = '';
    searchForm.value.expireEnd = '';
  }
  getTableList()
}
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 下载
const DebounceGetTemplates = debounce(getTemplates, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
// 导入
const DebounceImportSerial = customPromiseDebounce(importSerial, 1000, true);
// 转移
const DebounceTransforInfo = customPromiseDebounce(transferSerial, 1000, true);
</script>
<style lang="scss" scoped></style>
